﻿using System;
using System.IO;
using System.Windows.Media.Imaging;
using Google.GData.Photos;
using Microsoft.Samples.Kinect.KinectExplorer;
using Microsoft.Samples.Kinect.WpfViewers;

namespace SVU.Managers
{

    public class PicassaManager
    {
        
        private static PicasaService picasaService;
        const string picassaAlbumURL = @"https://picasaweb.google.com/data/feed/api/user/jfluckiger/albumid/5680218572688776737";

        // only upload one file at a time
        private static bool _isUploading;
        private static int countUpload;

        public static void UploadImageToPicassa(BitmapSource source)
        {
            // only upload ever 10 seconds
            if (!SvuConstants.AuthenticationCountDownTimer.Enabled)
                return;
            if (_isUploading)
                return;
            if (SvuConstants.LastUploadDate != DateTime.MinValue &&
                DateTime.Now.AddSeconds(-10) < SvuConstants.LastUploadDate)
                return;
            SvuConstants.LastUploadDate = DateTime.Now;

            // save to disk
            string tempImageFileName = Path.GetTempFileName() +"svu.bmp";

            using (FileStream fileStream = new FileStream(tempImageFileName, FileMode.Create))
            {
                BmpBitmapEncoder encoder = new BmpBitmapEncoder();
                KinectDiagnosticViewer.Instance.Dispatcher.Invoke(new Action(() => encoder.Frames.Add(BitmapFrame.Create(source))));
                encoder.Save(fileStream);
            }

            Action<string> a = SaveToDiskAndUpload;
            a.BeginInvoke(tempImageFileName, null, null);

        }

        private static void SaveToDiskAndUpload(string imageFileName)
        {
            if (_isUploading)
                return;

            try
            {
                _isUploading = true;

                // Initialize Picassa Service
                initializePicassaService();

                // Upload
                using (FileStream fileStream = new FileInfo(imageFileName).OpenRead())
                {
                    PicasaEntry entry = new PhotoEntry()
                                            {
                                                MediaSource =
                                                    new Google.GData.Client.MediaFileSource(fileStream, imageFileName,"image/bmp")
                                            };

                    PicasaEntry result = picasaService.Insert(new Uri(picassaAlbumURL), entry);
                    countUpload++;
                    FeedbackManager.AddFeedback("uploaded image " + countUpload);
                }
            }
            finally
            {
                _isUploading = false;
                File.Delete(imageFileName);
            }
        }
        
        private static object initializePicassaServiceLock = new object();
        private static void initializePicassaService()
        {
            if (picasaService == null)
            {
                lock (initializePicassaServiceLock)
                {
                    if (picasaService == null)
                    {
                        picasaService = new PicasaService("SVU");
                        picasaService.setUserCredentials("jfluckiger@gmail.com", "Bubble77");
                        string authToken = picasaService.QueryClientLoginToken();
                        picasaService.SetAuthenticationToken(authToken);
                    }
                }
            }
        }

    }
}
